package com.leetcode.partition3;

import java.util.ArrayList;
import java.util.List;

/**
 * @author `RKC`
 * @date 2021/8/13 9:20
 */
public class LC216组合总和3 {

    public static List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> result = new ArrayList<>();
        backtracking(1, result, new ArrayList<>(), k, n, 0);
        return result;
    }

    public static void main(String[] args) {
        System.out.println(combinationSum3(9, 45));
    }

    private static void backtracking(int startIndex, List<List<Integer>> result, List<Integer> path, int k, int n, int pathSum) {
        //剪枝操作，当前路径和大于n，就已经没有必要继续遍历了
        if (pathSum > n) return;
        if (path.size() == k) {
            if (pathSum == n) result.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {
            path.add(i);
            pathSum += i;
            backtracking(i + 1, result, path, k, n, pathSum);
            path.remove(path.size() - 1);
            pathSum -= i;
        }
    }
}
